import {
  defineComponent,
  reactive,
  onMounted,
  watchEffect, onUnmounted
} from "vue";
import Skeleton from "@/components/Skeleton";
import Card from "@/components/Card";
import Map from "./Map";
import {
  energyProportion,
  pmsFn,
  wuziFn,
  jingtaiFn,
  wlaqzelsFn, mbzjfubFn,
} from "./chart";

import "./style.less";
import { list1, list2 } from "./data.json";
import axios from "axios";
import {box} from "echarts/types/src/util/layout";

interface State {
  title?: string;
  mapType?: string;
  isInfoBox?: boolean;
  shuzihua: any[];
  huodongNumber: any[];
  scrollInterval: number;
  tableData: any[];
  tableName: string;
  tableType: 1 | 2;
  dataTitle: string;
  dataType: 1 | 2;
  mbzjfubFnData:{
    dtos: any[],
    name: string,
    names: any[],
    type: any,
    values: any[],
  },
  flowRatio: any,
  circleBoxData: any[],
  flowCount: number,
  businessIntegrationTimer: any
}

export default defineComponent(() => {
  const state = reactive<State>({
    title: "智护视界流量数据可视化",
    mapType: "bg2",
    isInfoBox: true,
    shuzihua: [
      { color: "#218FF7", name: "推广任务数", value: 19, icon: "icon-1.png" },
      { color: "#00FF96", name: "典型案例", value: 11, icon: "icon-2.png" },
      { color: "#FFE16A", name: "优秀典型案例", value: 1, icon: "icon-3.png" },
    ],
    huodongNumber: [
      {
        color: "#218FF7",
        name: "活动总数",
        value: 5,
        icon: ["icon-5.png", "blue.png"],
      },
      {
        color: "#00FF96",
        name: "竞赛类",
        value: 3,
        icon: ["icon-6.png", "green.png"],
      },
      {
        color: "#218FF7",
        name: "创新类",
        value: 2,
        icon: ["icon-7.png", "blue.png"],
      },
    ],
    scrollInterval: 0,
    tableData: [],
    tableName: "流量状态数据表",
    tableType: 1,

    dataTitle: "数据主人制认定情况-按专业",
    dataType: 1,
    businessIntegrationTimer: null,
    mbzjfubFnData:{
      dtos: [],
      name: "",
      names: [],
      type: null,
      values: [],
    },
    flowRatio: null,
    circleBoxData: [],
    flowCount: 0,
  });

  const getImageUrl = (name: string) => {
    return new URL(`../../assets/business-integration/${name}`, import.meta.url)
      .href;
  };
  /**
   * 监听某个状态的改变
   */
  watchEffect(
    (onInvalidate) => {
      /**
       * 当组件失效，watchEffect被主动停止或者副作用即将重新执行时，这个函数会执行
       */
      onInvalidate(() => {});
    },
    {
      /**
       * post: 在组件更新后触发，这样你就可以访问更新的 DOM。
       * pre: 默认值，在组件更新前触发
       * sync: 同步触发，低效
       */
      flush: "post",
    }
  );

  const onChangeData = () => {
    if (state.dataType === 1) {
      state.dataTitle = "数据主人制认定情况-按组织机构";
      state.dataType = 2;

      setTimeout(() => {
        wlaqzelsFn();
      }, 0);
    } else {
      state.dataTitle = "数据主人制认定情况-按专业";
      state.dataType = 1;
    }
  };

  const changeTableFn = () => {
    if (state.tableType === 1) {
      state.tableData = list2;
      state.tableName = "营销专业台区智能终端覆盖情况表";
      state.tableType = 2;
    } else {
      state.tableData = list1;
      state.tableName = "配网专业台区智能终端覆盖情况表";
      state.tableType = 1;
    }

    const tbody = document.querySelector(".scrollable-tbody") as HTMLElement;
    tbody.scrollTop = 0;
  };

  const getTableData = async () => {
    const res: any = await axios.post("http://localhost:8080/x_TableData");
    state.flowCount = res.data.data.count1;
    console.log(state.flowCount,"flowCount")
    state.tableData = res.data.data.l1;
  }

  const getFlowRatio = async () => {
    const res: any = await axios.post("http://localhost:8080/flowRatio");
    let num:number = 0;
    state.flowRatio = res.data.data;
    state.flowRatio.dtos.forEach((item:any)=>{
      num += item.value;
    })
    state.flowRatio.dtos.forEach((item:any,index:number)=>{
      state.circleBoxData.push({
        title:  `当前流量${item.name}率`,
        // value: (state.flowRatio.values[0] / (state.flowRatio.values[0] + state.flowRatio.values[1]) * 100).toFixed(2),
        value: (item.value / num * 100).toFixed(0),
        color: index ? "rgba(255, 92, 92, 1)" : "rgba(55, 255, 201, 1)",
      },)
    })
  }

  onUnmounted(() => {
    clearInterval(state.businessIntegrationTimer)
  })

  const initData = async () => {
    await jingtaiFn();
    state.mbzjfubFnData = await mbzjfubFn();
    await getFlowRatio();
    await pmsFn();
    await wuziFn();
  }

  onMounted(async () => {
    await initData();
    await getTableData();
    state.businessIntegrationTimer = setInterval(async ()=>{
      await initData();
    },10000)

    /**
     * 表格自动滚动
     */
    const tbody = document.querySelector(".scrollable-tbody") as HTMLElement;

    function startAutoScroll() {
      state.scrollInterval = setInterval(() => {
        tbody.scrollTop += 1; // 修改这个值以调整滚动速度
        /**
         * 滚动到末尾自动回到顶部
         */
        if (tbody.scrollTop >= tbody.scrollHeight - tbody.clientHeight) {
          tbody.scrollTop = 0;
        }
      }, 20); // 修改这个值以调整滚动频率
    }

    function stopAutoScroll() {
      clearInterval(state.scrollInterval);
    }

    // 鼠标移入暂停滚动
    tbody.addEventListener("mouseenter", stopAutoScroll);

    // 鼠标移出恢复滚动
    tbody.addEventListener("mouseleave", startAutoScroll);

    // 页面加载完毕开始自动滚动
    startAutoScroll();
  });

  return () => {
    const { title, mapType, flowCount } = state;

    return (
      <Skeleton title={title} mapType={mapType}>
        <div class="business-integration">
          <div class="bi-left">
            <Card title="协议和攻击次数" style="height: 40%;">
              <div class="part">
                <div class="chart" id="jingtai"></div>
              </div>
            </Card>
            <Card
              title="目标主机服务比"
              style="margin-top: 30px;height: calc(54% - 30px);"
              class="abnormal-data-key"
            >
              <div class="part">
                <div class="chart" id="mbzjfub"></div>
                <div class="szhnlkapt-title">数据情况</div>
                <div class="chart_item" style="flex-direction: column;">
                  <div class="tips">
                    <div class="tips_item">
                      <span class="label">{state.mbzjfubFnData.names[0]}</span>
                      <span class="value">{state.mbzjfubFnData.values[0]}</span>
                      <span class="unit">次</span>
                    </div>
                    <div class="tips_item">
                      <span class="label">{state.mbzjfubFnData.names[1]}</span>
                      <span class="value" style="color: rgba(60, 255, 223, 1)">
                        {state.mbzjfubFnData.values[1]}
                      </span>
                      <span class="unit">次</span>
                    </div>
                    <div class="tips_item">
                      <span class="label">{state.mbzjfubFnData.names[2]}</span>
                      <span
                        class="value"
                        style="color: rgba(255, 249, 105, 1);"
                      >
                        {state.mbzjfubFnData.values[2]}
                      </span>
                      <span class="unit">次</span>
                    </div>
                    <div class="tips_item">
                      <span class="label">{state.mbzjfubFnData.names[3]}</span>
                      <span
                          class="value"
                          style="color: rgba(109, 148, 198, 1);"
                      >
                        {state.mbzjfubFnData.values[3]}
                      </span>
                      <span class="unit">次</span>
                    </div>
                    <div class="tips_item">
                      <span class="label">{state.mbzjfubFnData.names[4]}</span>
                      <span
                          class="value"
                          style="color: rgba(255, 255, 255,  1));"
                      >
                        {state.mbzjfubFnData.values[4]}
                      </span>
                      <span class="unit">次</span>
                    </div>
                  </div>

                  <div class="chart" id="wenti"></div>
                </div>
              </div>
            </Card>
          </div>
          <Map flowCount={flowCount} />
          <div class="bi-right">
            <Card title="当前流量状态" style="height: 28%;">
              <div
                class="szhnlkapt-title"
                style="cursor: pointer;"
              >
                {state.tableName}
                {/*<div class="triangle"></div>*/}
              </div>
              <div class="netdevice-gaojing">
                <table>
                  <thead>
                    <tr>
                      <th>序号</th>
                      <th>ID</th>
                      <th>时间</th>
                      <th>状态</th>
                    </tr>
                  </thead>
                  <tbody class="scrollable-tbody">
                    {state.tableData.map((item, index) => {
                      return (
                        <tr>
                          <td title={index.toString()}>{index + 1}</td>
                          <td title={item.id}>{item.id}</td>
                          <td title={item.sj}>{item.sj}</td>
                          <td title={item.sjlx} style={item.sjlx == '异常' ? 'color: red' : ''}>{item.sjlx}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </Card>
            <Card
              title="当前流量状态比例"
              style="margin-top: 30px;height: calc(66% - 30px);"
            >
              <div class="part">
                {/*<div class="szhnlkapt-title">流量状态应用情况</div>*/}
                <div class="circle_box">
                  {
                    state.circleBoxData.map((item:any, index:any) => {
                    return (
                      <div class="ep-item">
                        <div
                          class={`ep-item_${index}`}
                          style="width: 100%; height: 100%"
                        >
                          {setTimeout(() => {
                            energyProportion(
                              `.ep-item_${index}`,
                              item.value,
                              item.color
                            );
                          }, 0)}
                        </div>
                        <span
                          class="epi-proportion"
                          style={{ color: item.color }}
                        >
                          {parseFloat(
                            ((item.value / 100) * 100).toFixed(2).toString()
                          )}
                          <p>%</p>
                        </span>
                        <span class="epi-title">{item.title}</span>
                      </div>
                    );
                  })}
                </div>
                <Card
                    title="目标主机攻击次数"
                    style="margin-top: 30px;height: 40%;"
                >
                  <div class="chart" id="mbzjgjcs" style="height:100%;width:100%"></div>
                </Card>
                <Card
                    title="流量异常时序分析"
                    style="margin-top: 30px;height: 40%;"
                >
                  <div class="chart" id="ldbdxfqs" style="height:100%;width:100%"></div>
                </Card>
              </div>
            </Card>
          </div>
        </div>
      </Skeleton>
    );
  };
});
